<template>
  <div class="quickAddPropertyInfo">
    <t-button theme="primary" variant="text" block @click="handleOpenDialog('create', { adCode: [] })">
      新建楼盘
    </t-button>
  </div>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData, readonly }"
    attach="body"
    :api-map="propertyManageCRUD"
    header="*楼盘"
    @request-success="handleDialogRequestSuccess"
    @close="emits('close')"
  >
    <t-form-item label="楼盘名称" name="propertyName" :rules="[{ required: true, message: '请选择楼盘名称' }]">
      <t-select
        v-model:value="formData.propertyName"
        v-model:input-value="formData.inputValue"
        placeholder="请选择楼盘名称"
        clearable
        filterable
        :readonly="readonly"
        :loading="loadingPropertyName"
        @search="handleResetSearchPropertyName"
        @change="(value) => handleChangePropertyName(value, formData)"
      >
        <t-option v-for="_ in propertyList" :key="_.id" :value="_.id" :label="_.title">
          {{ _.title }}
          <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
        </t-option>
        <template #panelBottomContent>
          <t-button
            v-show="pagination.count && pagination.count > propertyList.length"
            theme="primary"
            variant="text"
            block
            @click="handleSearchPropertyName(formData.inputValue)"
          >
            加载更多
          </t-button>
        </template>
      </t-select>
    </t-form-item>
    <template v-if="formData.propertyName">
      <t-form-item label="详细地址" name="address">
        <t-textarea v-model:value="formData.address" placeholder="请输入详细地址" :readonly="readonly" />
      </t-form-item>
      <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
        <t-cascader
          v-model:value="formData.adCode"
          :options="city.tree"
          :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
          placeholder="请选择归属城市"
          filterable
          clearable
          :readonly="readonly"
          value-type="full"
          @change="(value: any) => handleAdCodeChange(value, formData)"
        />
      </t-form-item>
      <t-form-item label="经度" name="longitude" :rules="[{ required: true, message: '请输入经度' }]">
        <t-input-number
          v-model:value="formData.longitude"
          placeholder="请输入经度"
          clearable
          :readonly="readonly"
          theme="normal"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="纬度" name="latitude" :rules="[{ required: true, message: '请输入纬度' }]">
        <t-input-number
          v-model:value="formData.latitude"
          placeholder="请输入纬度"
          clearable
          :readonly="readonly"
          theme="normal"
          style="width: 100%"
        />
      </t-form-item>
    </template>
  </custom-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin, SelectValue } from 'tdesign-vue-next';
import { reactive, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD, searchPropertyListByKeyword } from '@/api/config/property';
import CustomDialog from '@/components/custom/dialog/index.vue';
import city from '@/utils/city';

// emits
const emits = defineEmits(['open', 'close']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
  emits('open');
};
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  emits('close');
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.provinceCode = value[0] || '';
  params.cityCode = value[1] || '';
  params.areaCode = value[2] || '';
};
// 加载楼盘名称
const loadingPropertyName = ref(false);
// 楼盘列表
const propertyList = ref([]);
// 分页
const pagination = reactive({
  pageIndex: 1,
  count: 0,
});
// 处理搜索楼盘名称
const handleSearchPropertyName = (keyword: string) => {
  if (!keyword) return;
  loadingPropertyName.value = true;
  const params = { keyword, pageIndex: pagination.pageIndex };
  searchPropertyListByKeyword(params)
    .then((data) => {
      data = JSON.parse(data);
      propertyList.value.push(...data.data);
      pagination.pageIndex++;
      pagination.count = data.count;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loadingPropertyName.value = false;
    });
};
// 处理重置搜索楼盘名称
const handleResetSearchPropertyName = (keyword: string) => {
  propertyList.value = [];
  pagination.pageIndex = 1;
  pagination.count = 0;
  handleSearchPropertyName(keyword);
};
// 处理改变楼盘名称
const handleChangePropertyName = (value: SelectValue, formData: Record<string, any>) => {
  if (!value) return;
  const propertyInfo = propertyList.value.find((item) => item.id === value);
  formData.name = propertyInfo.title;
  formData.address = propertyInfo.address;
  formData.longitude = propertyInfo.location.lng;
  formData.latitude = propertyInfo.location.lat;
  formData.provinceCode = `${propertyInfo.adcode.toString().substring(0, 2)}0000`;
  formData.cityCode = `${propertyInfo.adcode.toString().substring(0, 4)}00`;
  formData.areaCode = propertyInfo.adcode.toString();
  formData.adCode = [formData.provinceCode, formData.cityCode, formData.areaCode];
};
</script>

<style lang="less" scoped>
.quickAddPropertyInfo {
  border-top: 1px solid var(--td-component-stroke);
  padding: 6px;
}
</style>
